<template>
  <div id="app">
    <!-- <div style="position:fixed;left:0;top:0;z-index:100;">{{$store.state.progress}}</div> -->
    <!-- <div style="-webkit-app-drag: drag">拖动</div> -->

    <!-- 左侧 -->
    <div class="app-left">
      <div class="logo">Muse</div>

      <!-- 左侧菜单栏 -->
      <el-menu
        :router="true"
        :active-text-color="activeTextColor"
        :text-color="textColor"
        :background-color="backgroundColor"
        default-active="/search"
        class="el-menu-vertical-demo"
      >
        <el-menu-item-group title="在线音乐">
          <el-menu-item index="/search">搜索</el-menu-item>
          <el-menu-item index="2">歌单</el-menu-item>
          <el-menu-item index="3">排行榜</el-menu-item>
        </el-menu-item-group>

        <el-menu-item-group title="我的音乐">
          <el-menu-item index="/PlayList">试听列表</el-menu-item>
        </el-menu-item-group>

        <el-menu-item-group title="其他">
          <el-menu-item index="/downloadManager">下载管理</el-menu-item>
          <el-menu-item index="7">设置</el-menu-item>
        </el-menu-item-group>
      </el-menu>
    </div>

    <!-- 右侧 -->
    <div class="app-right">
      <!-- 右上搜索栏、关闭按钮、最小化按钮 -->
      <div class="frame">
        <!-- 搜索栏 -->
        <el-autocomplete
          suffix-icon="el-icon-search"
          class="inline-input"
          v-model="keyword"
          placeholder="请输入内容"
          :trigger-on-focus="false"
          :fetch-suggestions="querySearch"
          @select="handleSelect"
          @change="onchangeHandler"
          :clearable="true"
        ></el-autocomplete>

        <div class="muse_drag">点我拖动</div>

        <!-- 关闭按钮、最小化按钮 -->
        <div class="btns">
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-minus"
            circle
            @click="windowMinimize"
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-close"
            circle
            @click="windowClose"
          ></el-button>
        </div>
      </div>

      <!-- 路由容器 -->
      <div v-if="!$route.meta.isFinish">敬请期待</div>
      <keep-alive>
        <router-view v-if="$route.meta.keepAlive"></router-view>
      </keep-alive>
      <router-view v-if="!$route.meta.keepAlive"></router-view>

      <!-- 播放器 -->
      <div class="playerBox">
        <player
          :mode.sync="$store.state.mode"
          :isPlaying.sync="$store.state.isPlaying"
          :lyric="$store.state.lyric"
          :musicSrc="$store.state.musicSrc"
          :volume.sync="$store.state.volume"
          :progress.sync="$store.state.progress"
          :totalTime="$store.state.totalTime"
          :artist="$store.state.artist"
          :name="$store.state.name"
          :imgsrc="$store.state.imgsrc"
          :borderWidth="2"
          @onended="onendedHandler"
          @onnextClick="nextSong"
          @onprevClick="prevSong"
        ></player>
      </div>
    </div>
  </div>
</template>
<script>
// 一定要window.require引入
let { ipcRenderer } = window.require("electron");
let fs = window.require("fs");

import vuex from "vuex";

const kuwoapi = vuex.createNamespacedHelpers("kuwoapi");
const kuwoapiActions = kuwoapi.mapActions(["suggestSearch", "search"]);
const kuwoapiMutations = kuwoapi.mapMutations(["setState"]);

const wangyiyunapi = vuex.createNamespacedHelpers("wangyiyunapi");
const wangyiyunapiActions = wangyiyunapi.mapActions(["search"]);
const wangyiyunapiMutations = wangyiyunapi.mapMutations(["setState"]);

// 引入播放器组件
import player from "./components/player";

let vuexObj = {
  kuwo: {
    Actions: kuwoapiActions,
    Mutations: kuwoapiMutations,
  },
  wangyiyun: {
    Actions: wangyiyunapiActions,
    Mutations: wangyiyunapiMutations,
  },
};

// 引入方法
import music from "./function/music";

export default {
  data() {
    return {
      vuexObj,
      backgroundColor: "#4DAF7C",
      textColor: "#ffffff",
      activeTextColor: "#6f6084",
      keyword: "",
      timeout: null,
    };
  },

  methods: {
    // 播放按钮点击
    async playMusic(e) {
      music.playMusic(e, this);
    },

    // 下一曲
    nextSong(e) {
      // 获取播放列表
      let Muse_PlayList =
        ipcRenderer.sendSync("getStore", "Muse_PlayList") || [];

      if (Muse_PlayList.length !== 0) {
        this.$store.state.currentIndex += 1;
        this.$store.state.currentIndex %= Muse_PlayList.length;
      }
      this.playMusic(Muse_PlayList[this.$store.state.currentIndex]);
    },

    // 上一曲
    prevSong(e) {
      // 获取播放列表
      let Muse_PlayList =
        ipcRenderer.sendSync("getStore", "Muse_PlayList") || [];
      if (Muse_PlayList.length !== 0) {
      this.$store.state.currentIndex -= 1;
      if (this.$store.state.currentIndex < 0)
        this.$store.state.currentIndex = Muse_PlayList.length - 1;
      }
      this.playMusic(Muse_PlayList[this.$store.state.currentIndex]);
    },

    // 当前歌曲播放完毕
    onendedHandler(e) {
      if (this.$store.state.mode === 1) {
        this.nextSong(e);
      } else if (this.$store.state.mode === 2) {
        console.log("随机播放");
      }
    },

    // 加载搜索建议
    querySearch(queryString, cb) {
      // 防抖
      if (this.timeout) clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        // 调用酷我api的搜索建议
        // 调用 callback 返回建议列表的数据
        kuwoapiActions.suggestSearch
          .call(this, this.keyword)
          .then((res) => cb(res))
          .catch((err) => {
            if (err) {
              this.$message({
                type: "error",
                message: "网络出错",
              });
            }
          });
      }, 500);
    },

    // 选择搜索建议
    handleSelect(item) {
      this.keyword = item.value;
    },
    // 搜索
    async onchangeHandler() {
      // 延时：确保keyword更新
      await (() =>
        new Promise((resolve) => setTimeout(() => resolve(), 500)))();

      for (let key in this.vuexObj) {
        // 取出对象
        let value = this.vuexObj[key];
        // 调用setState方法开启加载动画
        value.Mutations.setState.call(this, { loading: true });

        // 开始对应的api搜索
        value.Actions.search
          .call(this, { keyword: this.keyword })
          .finally(() => {
            // 搜索成功关闭加载动画
            value.Mutations.setState.call(this, { loading: false });
          })
          .catch((err) => {
            if (err) {
              this.$message({
                type: "error",
                message: "网络出错",
              });
            }
          });
      }
    },

    // electron窗口最小化
    windowMinimize() {
      ipcRenderer.send("window-minimize");
    },

    // electron关闭窗口
    windowClose() {
      ipcRenderer.send("window-close");
    },
  },

  components: {
    player,
  },

  created() {
    // 获取播放列表
    let Muse_PlayList = ipcRenderer.sendSync("getStore", "Muse_PlayList") || [];
    // 播放第一首
    this.playMusic(Muse_PlayList[this.$store.state.currentIndex]);
    this.$store.commit("setState", { isPlaying: true });
  },
};
</script>

<style lang="scss">
// 清除默认样式
* {
  margin: 0;
  padding: 0;
  user-select: none;
}

// 应用程序盒子
#app {
  width: 900px;
  height: 570px;
  overflow: hidden;
  display: flex;
}

.app-left {
  background-color: #4daf7c;
}

.app-left .logo {
  font-size: 50px;
  color: #fff;
  // font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  // font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;
  font-family: Georgia, "Times New Roman", Times, serif;
  height: 70px;
  line-height: 70px;
  text-align: center;
  -webkit-app-region: drag;
}

// 左边导航栏菜单
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  height: 100%;
}
// 菜单分组字体颜色
.el-menu-item-group__title {
  color: #c7e6d5;
}
// 单个菜单
.el-menu-item {
  height: 46px;
  line-height: 46px;
  border-radius: 10px;
  text-indent: 1em;
}
// 输入框获得焦点
.el-input__inner:focus {
  border-color: #dcdfe6;
}
// 输入框高度
.el-input__inner {
  height: 30px;
  line-height: 30px;
}
// 输入框图标
.el-input__icon {
  line-height: 30px;
}
// 右上搜索栏、关闭按钮、最小化按钮盒子
.frame {
  padding: 10px;
  height: 30px;
  display: flex;
  justify-content: space-between;
}

.frame .muse_drag {
  font-size: 12px;
  height: 12px;
  line-height: 12px;
  color: #c7e6d5;
  opacity: 0;
  transition: all 0.5s linear;
  -webkit-app-region: drag;
}

.frame:hover .muse_drag {
  opacity: 1;
}

// 右半部分
.app-right {
  flex: 1;
}

.playerBox {
  width: 700px;
  position: fixed;
  right: 0;
  bottom: 0;
}
</style>
